<template>
  <div class="category-container">
    <div class="category-header">
      <el-button type="primary" @click="handleAdd(null)">新增分类</el-button>
    </div>

    <el-table
      :data="categoryList"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="分类名称" width="220" />
      <el-table-column prop="sort" label="排序" width="100" />
      <el-table-column prop="status" label="状态" width="400">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button type="primary" link @click="handleAdd(scope.row)" v-if="scope.row.level < 2">
              添加子分类
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)"> 编辑 </el-button>
            <el-button
              v-if="scope.row.parentId !== 0 || scope.row.children.length === 0"
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <!-- 启用/停用 -->
            <el-button
              v-if="scope.row.parentId !== 0 || scope.row.children.length === 0"
              type="primary"
              :class="{ 'el-button--success': scope.row.status === 1, 'el-button--error': scope.row.status === 0 }"
              link
              @click="handleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? "停用" : "启用" }}
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="上级分类">
          <el-cascader
            v-model="formData.parentId"
            :options="categoryOptions"
            :props="cascaderProps"
            clearable
            placeholder="请选择上级分类"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCategoryTreeList, addCategory, updateCategory, deleteCategory, enableCategory } from "@/api/category/index";

// 分类列表数据
const categoryList = ref([]);
// 分类选项（用于级联选择器）
const categoryOptions = ref([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增分类");
const formRef = ref(null);

// 表单数据
const formData = reactive({
  id: null,
  parentId: 0,
  name: "",
  sort: 0,
  status: 1,
  level: 1,
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序号", trigger: "blur" }],
};

// 级联选择器配置
const cascaderProps = {
  value: "id",
  label: "name",
  children: "children",
  checkStrictly: true,
  disabled: (node) => node.level >= 2,
};

// 获取分类列表
const getCategoryList = async () => {
  try {
    // 获取分类列表
    const res = await getCategoryTreeList();
    categoryList.value = res.data;
    // 更新级联选择器选项
    categoryOptions.value = JSON.parse(JSON.stringify(categoryList.value));
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
  }
};

// 新增分类
const handleAdd = (row) => {
  dialogTitle.value = "新增分类";
  dialogVisible.value = true;
  if (row) {
    formData.parentId = row.id;
    formData.level = row.level + 1;
  }
  console.log(formData);
};

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = "编辑分类";
  dialogVisible.value = true;
  Object.assign(formData, row);
  console.log(formData);
};

// 删除分类
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该分类吗？", "提示", {
      type: "warning",
    });
    // 删除分类
    const res = await deleteCategory(row.id);
    if (res.success) {
      ElMessage.success("删除成功");
      getCategoryList();
    } else {
      ElMessage.error("删除失败");
    }
  } catch (error) {
    console.error("删除分类失败:", error);
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res;
        // 判断是否为Array
        if (formData.parentId instanceof Array && formData.parentId.length > 0) {
          formData.parentId = formData.parentId[formData.parentId.length - 1];
        }
        formData.level = formData.parentId ? getLevelById(formData.parentId) : 1;
        if (formData.id) {
          res = await updateCategory(formData);
          ElMessage.success("修改成功");
        } else {
          res = await addCategory(formData);
          ElMessage.success("添加成功");
        }
        if (res.success) {
          dialogVisible.value = false;
          getCategoryList();
        } else {
          if (formData.id) {
            ElMessage.error("修改失败");
          } else {
            ElMessage.error("添加失败");
          }
        }
      } catch (error) {
        console.error("保存分类失败:", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

const handleStatus = async (row) => {
  try {
    const res = await enableCategory(row.id, row.status === 1 ? 0 : 1);
    const statusText = row.status === 1 ? "停用" : "启用";
    if (res.success) {
      ElMessage.success(statusText + "成功");
      getCategoryList();
    } else {
      ElMessage.error(statusText + "失败");
    }
  } catch (error) {
    console.error("修改状态失败:", error);
    ElMessage.error("修改失败");
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    id: null,
    parentId: null,
    name: "",
    sort: 0,
    status: 1,
    level: 0,
  });
};

// 根据父分类id查询level
const getLevelById = (parentId) => {
  if (!parentId) return 1;
  let level = 1;
  const findLevel = (parentId) => {
    const parent = categoryList.value.find((item) => item.id === parentId);
    if (parent) {
      level++;
      findLevel(parent.parentId);
    }
  };
  findLevel(parentId);
  return level;
};

// 页面加载时获取分类列表
onMounted(() => {
  getCategoryList();
});
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.category-header {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
